import { useGlobalData } from "@/store/app";
import { useState, useEffect, useRef } from "react";
import { CHAT_SCROLL_VIEW_BOTTOM_FIXATION } from "./store";

function useIndex() {
  const { systemInfo } = useGlobalData();

  // scroll 高度
  const [height, setHeight] = useState(systemInfo.windowHeight);
  // 是否展示回到底部
  const [showBack, setShowBack] = useState(false);
  const scrollRef = useRef(0);
  const [scrollIntoView, setScrollIntoView] = useState("");
  const onScrollToLower = () => {
    console.log("updateScrollTop onScrollToLower clear");
    if (scrollIntoView) {
      setScrollIntoView("");
    }
  };
  const scrollToBottom = () => {
    setScrollIntoView(CHAT_SCROLL_VIEW_BOTTOM_FIXATION);
    if (scrollIntoView) {
      setScrollIntoView("");
    }
  };

  const onScroll = (e) => {
    // 获取滚动事件参数
    const { scrollTop, scrollHeight } = e.detail;
    scrollRef.current = scrollTop;
    // 判断是否滚动到底部
    if (scrollTop + height >= scrollHeight) {
      setShowBack(false);
    } else {
      setShowBack(true);
    }
  };

  useEffect(() => {
    const { windowHeight, statusBarHeight, navbarHeight } = systemInfo;
    const cHeight = windowHeight - statusBarHeight - navbarHeight;
    setHeight(cHeight);
  }, [systemInfo]);

  console.log("updateScrollTop scrollIntoVie==>", scrollIntoView);

  useEffect(() => {
    console.log("设备屏幕高度：" + systemInfo.windowHeight);
  }, []);

  return {
    scrollIntoView,
    showBack,
    scrollRef,
    onScrollToLower,
    scrollToBottom,
    onScroll,
  };
}

export default useIndex;
